import { Component } from '@angular/core';
import { Nav, NavParams, Events } from 'ionic-angular';
import { ModalController, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { SuperTabsController } from "ionic2-super-tabs";
import { TranslateService } from '@ngx-translate/core';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { File } from '@ionic-native/file';

import { ProductOptionModalPage } from '../product-option-modal/product-option-modal';
import { ActivatePage } from '../activate/activate';
import { LoginPage } from '../login/login';
import { ProductListPage } from '../product-list/product-list';
import { TableListPage } from '../table-list/table-list';
import { HelperService } from "../../providers/services.helper";
import { ApiService } from "../../providers/services.api";
import { GlobalData } from "../../providers/GlobalData";
import { PrinterService } from "../../providers/services.printer";

@Component({
  selector: 'page-home,slice-string-pipe',
  templateUrl: 'home.html'
})
export class HomePage {

  productListPage: any = ProductListPage;
  categoryList: Array<{ id: number, name: string }>;
  servingList: any;
  servingListCount: number;
  summaryCollapsed: boolean = true;
  servingLimit: number;
  servingLimitFrom: number;

  fileTransfer: TransferObject = this.transfer.create();

  serveStatus: Array<{ id: number, name: string, translateKey: string }> = [
    { id: 0, name: 'Ordered', translateKey: 'ORDERED' },
    { id: 1, name: 'Served', translateKey: 'SERVED' },
    { id: 2, name: 'Preparing', translateKey: 'PREPARING' }
  ];

  constructor(public navCtrl: Nav,
    public modalCtrl: ModalController,
    private storage: Storage,
    private transfer: Transfer,
    private file: File,
    public events: Events,
    public alertCtrl: AlertController,
    public translate: TranslateService,
    private superTabsCtrl: SuperTabsController,
    private helperService: HelperService,
    private printer: PrinterService,
    public navParams: NavParams,
    public api: ApiService,
    public global: GlobalData) {
    this.init();

  }

  init() {
    this.initCart();
    this.servingLimit = 40;
    this.servingLimitFrom = 0;

    this.servingList = [];
    this.servingListCount = 0;

  }

  downloadImage(url, targetName) {
    return new Promise((resolve, reject) => {
      this.fileTransfer.download(url, this.helperService.getRootPath() + targetName).then((entry) => {
        console.log('download complete: ' + entry.toURL());
        resolve(entry.toURL());
      }, (error) => {
        reject(error);
      });
    });
  }

  // toggle order summary
  toggleSummary(isSummary) {
    if (this.summaryCollapsed && this.global.curTab == 'serving') {
      this.loadServingList('init', null);
    }

    if (isSummary) {
      this.summaryCollapsed = isSummary;
    } else {
      this.summaryCollapsed = !this.summaryCollapsed;
    }
  }

  // toggle current tab
  toggleCurTab(type) {
    if (this.summaryCollapsed)
      this.toggleSummary(false);
    if (this.global.curTab == type) {
      return;
    }
    if (type == 'order' && this.global.curCart.id == null) {
      this.helperService.showToast(this.translate.instant('THIS_CART_IS_EMPTY'));
      return;
    }
    if (type == 'serving') {
      this.loadServingList('init', null);
    }
    this.global.curTab = type;
  }

  ngOnInit() {
    console.log('ngOnInit homePage');
    this.initGlobalData();
  }

  ionViewDidEnter() {
    console.log('ionViewDidEnter homePage');

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad homePage');

  }

  ngAfterViewInit() {
    this.initListener();
    this.generateTableData();
    this.initHomeData();
  }

  initGlobalData() {
    this.storage.get('activate').then(activate => {

      if (this.global.shopIconFile == '') {
        this.downloadImage(activate.shop_icon, 'shop_icon.png').then(success => {
          this.global.shopIconFile = 'shop_icon.png';
        }, error => {
          console.log('download shop icon error', error);
        });
      }
    });

    this.storage.get('user').then(user => {
      this.global.curUser = user;
      this.global.warehouse = user.warehouse;
    });

    this.storage.get('settings').then(setting => {
      if (setting.sandbox_mode) {
        this.global.curEnvir = 'SANDBOX_MODE';
      } else {
        this.global.curEnvir = 'PRODUCTION_MODE';
      }

      if (setting.online_mode) {
        this.global.curMode = 'ONLINE_MODE';
      } else {
        this.global.curMode = 'OFFLINE_MODE';
      }

      this.global.curEpsonPrinters = setting.epsonPrinters;
      this.global.curLang = setting.locale;
      this.global.curPrintLang = setting.print_locale;
      this.global.departments = setting.departments;
      this.global.isPrintByDepartment = setting.is_print_by_department;
      this.translate.use(this.global.curLang);

      console.log('initGlobalData', this.global.curEpsonPrinters);
    });
  }

  initHomeData() {
    this.loadCategory();
  };

  initListener(): void {
    console.log('register access_denined listener');
    this.events.subscribe('access_denined', time => {
      console.log('Access Denined', 'at', time);
      this.storage.get('user').then((user) => {
        user.isLogin = false;
        this.storage.set('user', user);
      });
      this.navCtrl.setRoot(LoginPage);
    });
    this.events.subscribe('editcart:resetoption', (option, time) => {
      this.resetOption(option);

    });
    this.events.subscribe('editcart:selectoption', (option, time) => {
      this.selectOption(option);

    });
  }

  loadCategory() {
    this.storage.get('settings').then(setting => {
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      // urlSearchParams.append('shop_id', setting.shop_id);
      this.api.getCategory(urlSearchParams.toString()).then(category => {
        console.log('getCategory success:', category['data'].length);
        this.categoryList = [];
        for (let ct of category['data']) {
          this.categoryList.push(ct);
        }
        this.superTabsCtrl.showToolbar(true);
        this.superTabsCtrl.enableTabsSwipe(true);
      }, (error) => {
        console.log('getCategory error:' + error);
        this.helperService.showToast(error);
      });
    });
  }

  loadServingList(mode, doer) {
    console.log("load serving mode :" + mode + ", in loadServingList count :" + this.servingListCount);

    if (mode != 'more' || this.servingList.length == 0) {
      this.servingLimitFrom = 0;
      this.servingLimit = 40;
      this.servingListCount = 0;
    } else {
      this.servingLimitFrom += this.servingLimit;
    }

    this.storage.get('settings').then(setting => {
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      urlSearchParams.append('limit_from', this.servingLimitFrom.toString());
      urlSearchParams.append('limit', '-1');
      urlSearchParams.append('warehouse_id', setting.warehouse_id);
      urlSearchParams.append('status[0]', '0');
      urlSearchParams.append('status[1]', '2');
      urlSearchParams.append('calling_type', 'f_b');
      this.api.getServingList(urlSearchParams.toString()).then(serving => {
        this.servingListCount = serving['data']['count'];
        if (mode != 'more' || this.servingList.length == 0) {
          this.servingList = [];
        }
        for (let sv of serving['data']['list']) {
          this.servingList.push(sv);
        }
        if (doer != null) {
          doer.complete();
        }
        console.log('getServingList success: ', this.servingList.length);
      }, (error) => {
        console.log('getServingList error: ' + error);
        if (doer != null) {
          doer.complete();
        }
        this.helperService.showToast(error);
      });
    });
  }

  loadServingCart(serving) {
    console.log(serving);
    this.global.curTab = 'order';
    this.loadCart(serving.id, null);
  }

  loadCart(invoice_id, doer) {
    return new Promise((resolve, reject) => {
      this.storage.get('settings').then(setting => {
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('locale', setting.locale);
        urlSearchParams.append('token', setting.token);
        urlSearchParams.append('warehouse_id', setting.warehouse_id);
        urlSearchParams.append('action', 'read');
        urlSearchParams.append('invoice_id', invoice_id);
        urlSearchParams.append('calling_type', 'f_b');
        this.api.setCart(urlSearchParams.toString()).then(cart => {
          this.global.curCart = cart['data'];
          console.log('loadCart success: ', cart['data']['id']);
          console.log(this.global.curCart);
          resolve(cart);
          if (doer != null) {
            doer.complete();
          }
        }, error => {
          console.log('loadCart error:' + error);
          this.helperService.showToast(error);
          reject(error);
          if (doer != null) {
            doer.complete();
          }
        });
      });
    });
  }

  clearCart() {
    console.log('clear cart:', this.global.curCart);
    if (this.global.curCart.payed_amount > 0) {
      this.helperService.showToast(this.translate.instant('THIS_CART_IS_PAYED'));
      return;
    }

    if (this.global.curCart.products.length == 0) {
      this.helperService.showToast(this.translate.instant('THIS_CART_IS_EMPTY'));
      return;
    }
    let alert = this.alertCtrl.create({
      title: this.translate.instant('REMIND'),
      message: this.translate.instant('CLICK_CLEAR_TO_CLEAR_CART'),
      buttons: [
        {
          text: this.translate.instant('CANCEL'),
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: this.translate.instant('CLEAR_'),
          handler: () => {
            console.log('Confirm clicked');
            this.helperService.showLoading();
            this.storage.get('settings').then(setting => {
              let urlSearchParams = new URLSearchParams();
              urlSearchParams.append('locale', setting.locale);
              urlSearchParams.append('token', setting.token);
              urlSearchParams.append('warehouse_id', setting.warehouse_id);
              urlSearchParams.append('action', 'empty');
              urlSearchParams.append('invoice_id', this.global.curCart.id);
              urlSearchParams.append('calling_type', 'f_b');
              this.api.setCart(urlSearchParams.toString()).then(cart => {
                this.helperService.hideLoading();
                this.global.curCart = cart['data'];
                this.loadServingList('init', null);
              }, (error) => {
                console.log('removeCartItem error:' + error);
                this.helperService.hideLoading();
                this.helperService.showToast(error);
              });
            });
          }
        }
      ]
    });
    alert.present();
  }

  saveCart() {
    this.helperService.showToast(this.translate.instant('HOLD_SUCCESS'));
    this.global.curTab = 'serving';
    this.initCart();
  }

  initCart() {
    this.global.curCart = {
      "id": null,
      "invoice_no": null,
      "table_num": 0,
      "item_total": 0,
      "discount_total": 0,
      "delivery_total": 0,
      "service_total": 0,
      "temp_grand_total": 0,
      "payed_amount": 0,
      "products": [],
      "invoice_charges": []
    };
  }

  newCart(table_num) {
    return new Promise((resolve, reject) => {
      this.storage.get('settings').then(setting => {
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('locale', setting.locale);
        urlSearchParams.append('token', setting.token);
        urlSearchParams.append('check_out_warehouse_id', setting.warehouse_id);
        urlSearchParams.append('user_id', this.global.curMember.user_id == 0 ? null : this.global.curMember.user_id);
        this.api.newCart(urlSearchParams.toString()).then(data => {
          console.log('newCart success:', data);
          resolve(data['invoice_id']);
        }, error => {
          console.log('newCart error:' + error);
          this.helperService.showToast(error);
          reject(error);
        });
      });
    });
  }

  editCartItem(item) {
    if (item.addons.length || item.options.length) {
      console.log(item, 'open item modal');
      this.global.product = item;
      this.openItemModal(item);
    }
  }

  openItemModal(product) {
    let productOptionModal = this.modalCtrl.create(ProductOptionModalPage, product);
    productOptionModal.onDidDismiss(data => {
      console.log(data);
    });
    productOptionModal.present();
  }

  selectOption(option) {
    console.log('selectOption:');
    console.log(option, this.global.product);
    this.helperService.showLoading();
    var addOptions: Array<{ dictionary: number, option: number }> = [];
    if (option['type'] == 'addons') {
      for (let addon of this.global.product.addons) {
        if (addon['id'] == option['id']) {
          addon['qty'] = option['qty'];
        }
      }
      for (let spec of this.global.product.specifications) {
        if (spec.enabled && spec.selectible && spec.options.length) {
          addOptions.push({
            dictionary: spec.dictionary,
            option: spec.options[0].id
          });
        }
      }
    }

    if (option['type'] == 'spec') {
      var i = 0;
      for (let j = 0; j < this.global.product['specifications'].length; j++) {
        if (this.global.product['specifications'][j]['enabled'] &&
          this.global.product['specifications'][j]['selectible'] &&
          this.global.product['specifications'][j]['options'].length) {

          for (let spe of this.global.product['specifications'][j]['options']) {
            if (spe['name'] == this.global.product['options'][j]['options'][0]) {
              addOptions.push({
                dictionary: this.global.product['specifications'][j]['dictionary'],
                option: option['dictionary'] == this.global.product['specifications'][j]['dictionary'] ? option['id'] : spe['id']
              });
            }
          }
        }
        i++;
      }
    }

    console.log('selectOption spec: ');
    console.log(addOptions);

    console.log('selectOption addons: ');
    console.log(this.global.product.addons);

    this.storage.get('settings').then(setting => {
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      urlSearchParams.append('warehouse_id', setting.warehouse_id);
      urlSearchParams.append('action', 'remove');
      urlSearchParams.append('invoice_id', this.global.curCart.id);
      urlSearchParams.append('product_id', this.global.product.id);
      urlSearchParams.append('item_id', this.global.product.item_id);
      urlSearchParams.append('calling_type', 'f_b');
      this.api.setCart(urlSearchParams.toString()).then(cart => {
        console.log('removeCartItem success:', cart);

        let urlSearchParams2 = new URLSearchParams();
        urlSearchParams2.append('locale', setting.locale);
        urlSearchParams2.append('token', setting.token);
        urlSearchParams2.append('warehouse_id', setting.warehouse_id);
        urlSearchParams2.append('action', 'add');
        urlSearchParams2.append('invoice_id', this.global.curCart.id);
        urlSearchParams2.append('qty', '1');
        urlSearchParams2.append('product_id', this.global.product.id);
        urlSearchParams2.append('addons', JSON.stringify(this.global.product.addons));
        urlSearchParams2.append('spec', JSON.stringify(addOptions));
        urlSearchParams2.append('invoice_charges', JSON.stringify(this.global.curCart.invoice_charges));
        urlSearchParams2.append('calling_type', 'f_b');
        this.api.setCart(urlSearchParams2.toString()).then(editCart => {
          this.global.curCart = editCart['data'];
          this.loadServingList('init', null);

          for (let pd of editCart['data']['products']) {
            if (pd['item_id'] == editCart['item_id']) {
              this.global.product = pd;
              console.log('set global product:' + pd);
            }
          }
          console.log('editCartItem success:', editCart);
          this.helperService.hideLoading();
        }, (error) => {
          console.log('editCartItem error:' + error);
          this.helperService.hideLoading();
          this.helperService.showToast(error);
        });
      }, (error) => {
        console.log('removeCartItem error:' + error);
        this.helperService.hideLoading();
        this.helperService.showToast(error);
      });
    });
  }

  slideChooseServe(item, info) {
    console.log(info);
    if (info != null) {
      this.helperService.showLoading();
    }
    var served = [];
    for (let product of this.global.curCart['products']) {
      if (info == null) {
        served.push({
          item_id: product.item_id,
          served: product.served == 0 ? 2 : product.served
        });
      } else {
        if (product.item_id == item['item_id']) {
          served.push({
            item_id: product.item_id,
            served: info.id
          });
        } else {
          served.push({
            item_id: product.item_id,
            served: product.served
          });
        }
      }
    }
    this.storage.get('settings').then(setting => {
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      urlSearchParams.append('warehouse_id', setting.warehouse_id);
      urlSearchParams.append('action', 'serve');
      urlSearchParams.append('served_item', JSON.stringify(served));
      urlSearchParams.append('invoice_id', this.global.curCart.id);
      urlSearchParams.append('calling_type', 'f_b');
      this.api.setCart(urlSearchParams.toString()).then(data => {
        // this.loadCart(this.global.curCart.id);
        // this.loadServingList('init', null);
        console.log('editCartServe success:', data);
        for (let product of this.global.curCart['products']) {
          for (let sev of served) {
            if (info == null) {
              if (product.served != 1) {
                product.served = 2;
              }
            } else {
              if ((product.item_id == item['item_id']) && (sev.item_id == item['item_id'])) {
                product.served = sev.served;
              }
            }
          }
        }
        if (served['payed'] && served['payed'] == 'Y') {
          console.log('pay & all served');
          this.initCart();
          this.loadServingList('init', null);
        }
        if (info != null) {
          this.helperService.hideLoading();
        }
      }, error => {
        console.log('editCartServe error:' + error);
        if (info != null) {
          this.helperService.hideLoading();
        }
        this.helperService.showToast(error);
      });
    });

  };

  voidCartItem(item) {
    let alert = this.alertCtrl.create({
      title: this.translate.instant('REMIND'),
      message: this.translate.instant('DELETE_CART_MSG'),
      buttons: [
        {
          text: this.translate.instant('CANCEL'),
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: this.translate.instant('CONFIRM'),
          handler: () => {
            console.log('Confirm clicked');
            this.helperService.showLoading();
            this.storage.get('settings').then(setting => {
              let urlSearchParams = new URLSearchParams();
              urlSearchParams.append('locale', setting.locale);
              urlSearchParams.append('token', setting.token);
              urlSearchParams.append('warehouse_id', setting.warehouse_id);
              urlSearchParams.append('action', 'remove');
              urlSearchParams.append('invoice_id', this.global.curCart.id);
              urlSearchParams.append('product_id', item.id);
              urlSearchParams.append('item_id', item.item_id);
              urlSearchParams.append('calling_type', 'f_b');
              this.api.setCart(urlSearchParams.toString()).then(cart => {
                this.helperService.hideLoading();
                this.loadCart(this.global.curCart.id, null);
                this.loadServingList('init', null);
              }, (error) => {
                console.log('removeCartItem error:' + error);
                this.helperService.hideLoading();
                this.helperService.showToast(error);
              });
            });
          }
        }
      ]
    });
    alert.present();
  }

  setTable(table_num) {
    console.log('setTable:', table_num, 'invoice id:', this.global.curCart.id);
    this.helperService.showLoading();
    if (table_num == this.global.curCart.table_num) {
      this.helperService.hideLoading();
      return;
    }
    this.storage.get('settings').then(setting => {
      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      urlSearchParams.append('warehouse_id', setting.warehouse_id);
      urlSearchParams.append('action', 'read');
      urlSearchParams.append('invoice_id', this.global.curCart.id);
      urlSearchParams.append('table_num', table_num);
      urlSearchParams.append('calling_type', 'f_b');
      this.api.setCart(urlSearchParams.toString()).then(cart => {
        console.log('setTable success:', cart);
        this.helperService.hideLoading();
        this.global.curCart = cart['data'];
        this.loadServingList('init', null);
      }, (error) => {
        console.log('setTable error:', error);
        this.helperService.showToast(error);
        this.helperService.hideLoading();
      });
    });
  }

  removeTable(table_num, invoice_id) {
    console.log('removeTable:', table_num, 'invoice id:', invoice_id);

  }

  resetOption(option) {
    console.log('resetOption:');
    console.log(option, this.global.product);

  }


  checkEveryServed = function (serve) {
    return serve.served != 0;
  };

  checkEveryNotServed = function (serve) {
    return serve.served == 0;
  };

  gotoPrintOrder() {
    var served = [];
    for (let product of this.global.curCart.products) {
      served.push({
        item_id: product.item_id,
        served: product.served
      });
    }
    if (served.every(this.checkEveryServed)) {
      console.log('Print All served');
      this.processCheckOut('order_all');

    } else if (served.every(this.checkEveryNotServed)) {
      console.log('Print All not served');
      this.processCheckOut('order');

    } else {
      this.processPrintOrder();
    }

  }

  processPrintOrder() {
    let alert = this.alertCtrl.create({
      title: this.translate.instant('REMIND'),
      message: this.translate.instant('ORDER_ADD_OR_ALL'),
      buttons: [
        {
          text: this.translate.instant('ADD_ORDER'),
          role: 'cancel',
          handler: () => {
            console.log('switch print order_add', 'ADD_ORDER');
            this.processCheckOut('order_add');
          }
        },
        {
          text: this.translate.instant('REPRINT'),
          handler: () => {
            console.log('switch print order_all', 'reprint');
            this.processCheckOut('order_all');
          }
        }
      ]
    });
    alert.present();
  }

  processCheckOut(type) {
    console.log(type);
    if (this.global.curCart.products.length < 1) {
      this.helperService.showToast(this.translate.instant('THIS_CART_IS_EMPTY'));
      return;
    }
    if (type == 'receipt' && this.global.curCart.payed_amount == 0) {
      type = 'invoice';
    }
    this.helperService.showLoading();
    this.storage.get('settings').then(setting => {
      let urlSearchParams = new URLSearchParams('');
      urlSearchParams.append('locale', setting.locale);
      urlSearchParams.append('token', setting.token);
      urlSearchParams.append('warehouse_id', setting.warehouse_id);
      urlSearchParams.append('invoice_id', this.global.curCart.id);
      urlSearchParams.append('invoice_charges', JSON.stringify(this.global.curCart.invoice_charges));
      urlSearchParams.append('delivery_type', this.global.curCart.delivery_type ? this.global.curCart.delivery_type : 'direct sales');
      urlSearchParams.append('user_id', this.global.curCart.user_id);
      urlSearchParams.append('calling_type', 'f_b');
      this.api.checkOut(urlSearchParams.toString()).then(data => {
        console.log('processCheckOut success:', data, this.global.curCart);
        let urlSearchParams2 = new URLSearchParams();
        urlSearchParams2.append('locale', setting.locale);
        urlSearchParams2.append('token', setting.token);
        urlSearchParams2.append('warehouse_id', setting.warehouse_id);
        urlSearchParams2.append('action', 'read');
        urlSearchParams2.append('invoice_id', data['data']['invoice_id']);
        urlSearchParams2.append('calling_type', 'f_b');
        this.api.setCart(urlSearchParams2.toString()).then(cart => {
          this.global.curCart = cart['data'];
          console.log('go to printDirect:', this.global.curCart);

          this.printer.printDirect(cart['data'], type);
          setTimeout(() => {
            this.slideChooseServe(cart['data'], null);
          }, 2000);
          this.helperService.hideLoading();
        }, error => {
          console.log('loadCart error:' + error);
          this.helperService.showToast(error);
          this.helperService.hideLoading();
        });
      }, (error) => {
        console.log('processCheckOut error:' + error);
        this.helperService.hideLoading();
        this.helperService.showToast(error);
      });
    });

  }

  // open new table
  openTable(tp) {
    if (tp == 'switchTable' && this.global.curCart.id == null) {
      tp = 'switchTable-new';
      // this.helperService.showToast(this.translate.instant('THIS_CART_IS_EMPTY'));
      // return;
    }
    this.generateTableData();
    this.helperService.showLoading();
    this.getTableInfo().then(tableList => {
      this.helperService.hideLoading();
      for (let red of tableList['red']) {
        for (let globalList of this.global.tableList) {
          if (globalList['id'] == red) {
            globalList['orders'] = tableList['table'][red - 1];
            for (let order of globalList['orders']) {
              for (let share of globalList['shared']) {
                if (order['table_num'] == share['name']) {
                  share['invoice_no'] = order['data']['id'];
                }
              }
            }
          }
        }
      }
      if (tp == 'switchTable-new') {
        tp = 'switchTable';
        let modal = this.modalCtrl.create(TableListPage, { type: tp });
        modal.onDidDismiss(table => {
          if (table != undefined && table != null) {
            this.loadCart(table['data']['id'], null);
          }
        });
        this.newCart(0).then(invoiceId => {
          this.global.curTab = 'order';
          this.global.curCart['id'] = invoiceId;
          modal.present();
        });
      } else {
        let modal = this.modalCtrl.create(TableListPage, { type: tp });
        modal.onDidDismiss(table => {
          if (table != undefined && table != null) {
            this.loadCart(table['data']['id'], null);
          }
        });
        modal.present();
      }
    }, error => {
      this.helperService.hideLoading();
    });
  }

  getTableInfo() {
    return new Promise((resolve, reject) => {
      this.storage.get('settings').then(setting => {
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('locale', setting.locale);
        urlSearchParams.append('token', setting.token);
        urlSearchParams.append('warehouse_id', setting.warehouse_id);
        urlSearchParams.append('table_total', this.global.tableAmount.toString());
        this.api.getTableInfo(urlSearchParams.toString()).then(tableList => {
          console.log('getTableInfo success:', tableList);
          resolve(tableList);
        }, error => {
          console.log('getTableInfo error:' + error);
          this.helperService.showToast(error);
          reject(error);
        });
      });
    });
  }

  generateTableData() {
    var tableList = [];
    this.storage.get('tableList').then(tList => {
      // if (tList == null || tList.length == 0) {
      console.log('generate table:');
      for (let i = 1; i < (this.global.tableAmount + 1); i++) {
        tableList.push({
          id: i,
          name: this.translate.instant('TABLE_NO') + i,
          total: 10,
          occupied: i,
          collapsed: true,
          orders: [],
          shared: [
            {
              id: -1,
              name: i,
              invoice_no: ''
            }, {
              id: 0,
              name: i + 'A',
              invoice_no: ''
            }, {
              id: 1,
              name: i + 'B',
              invoice_no: ''
            }, {
              id: 2,
              name: i + 'C',
              invoice_no: ''
            }, {
              id: 3,
              name: i + 'D',
              invoice_no: ''
            }, {
              id: 4,
              name: i + 'E',
              invoice_no: ''
            }, {
              id: 5,
              name: i + 'F',
              invoice_no: ''
            }, {
              id: 6,
              name: i + 'G',
              invoice_no: ''
            }, {
              id: 7,
              name: i + 'H',
              invoice_no: ''
            }, {
              id: 8,
              name: i + 'I',
              invoice_no: ''
            }, {
              id: 9,
              name: i + 'J',
              invoice_no: ''
            }, {
              id: 10,
              name: i + 'K',
              invoice_no: ''
            }, {
              id: 11,
              name: i + 'L',
              invoice_no: ''
            }, {
              id: 12,
              name: i + 'M',
              invoice_no: ''
            }, {
              id: 13,
              name: i + 'N',
              invoice_no: ''
            }, {
              id: 14,
              name: i + 'O',
              invoice_no: ''
            }, {
              id: 15,
              name: i + 'P',
              invoice_no: ''
            }, {
              id: 16,
              name: i + 'Q',
              invoice_no: ''
            }, {
              id: 17,
              name: i + 'R',
              invoice_no: ''
            }, {
              id: 18,
              name: i + 'S',
              invoice_no: ''
            }, {
              id: 19,
              name: i + 'T',
              invoice_no: ''
            }, {
              id: 20,
              name: i + 'U',
              invoice_no: ''
            }, {
              id: 21,
              name: i + 'V',
              invoice_no: ''
            }, {
              id: 22,
              name: i + 'W',
              invoice_no: ''
            }, {
              id: 23,
              name: i + 'X',
              invoice_no: ''
            }, {
              id: 24,
              name: i + 'Y',
              invoice_no: ''
            }, {
              id: 25,
              name: i + 'Z',
              invoice_no: ''
            }
          ]
        });
      }
      this.global.tableList = tableList;
      this.storage.set('tableList', tableList);
      // }
      // else {
      //   console.log('already have table:');
      //   this.global.tableList = tList;
      //   this.storage.set('tableList', tList);
      // }
    });
  }
}
